<template>
  <div class="discover">
    <!-- 轮播图  -->
    <div class="discover-Carousel">
      <div class="block">
        <el-carousel
          v-loading="discoverloading"
          element-loading-text="别急加载中..."
          element-loading-spinner="el-icon-loading"
          :interval="4000"
          type="card"
          trigger="click"
          height="231px"
        >
          <el-carousel-item v-for="(item,index) in extInfo" :key="index">
            <a :href="item.url">
              <img @click="playmusic(item)" :src="item.imageUrl+'?param=600y231'" alt />
            </a>
          </el-carousel-item>
        </el-carousel>
      </div>
    </div>
    <!-- 轮播图结束 -->
    <!-- 推荐歌单 -->
    <div class="discover-title">
      <router-link to="/findmusic/playlist">
        推荐歌单
        <a class="el-icon-arrow-right"></a>
      </router-link>
    </div>
    <div class="line"></div>
    <div class="discover-playlist">
      <playlistskeleton
        v-show="loading"
        class="discover-playlist-item"
        v-for="(item,index) in 10"
        :key="index+'skeleton'"
      />
      <playlistitem
        class="discover-playlist-item"
        :playitem="item"
        v-for="(item,index) in playlist"
        :key="index"
      />
    </div>
    <!-- 推荐歌单结束 -->
    <!-- 最新音乐 -->
    <div class="discover-title">
      最新音乐
      <a class="el-icon-arrow-right"></a>
    </div>
    <div class="line"></div>
    <div class="discover-newmusic">
      <!-- 歌曲信息 -->
      <musicItem
        class="newmusic-item"
        v-for="(item,index) of musics"
        @addPlaylist="addPlaylist"
        :currentMusic="item"
        :key="index+'music'"
      />
    </div>
    <!-- 最新音乐结束 -->
    <!-- 备案号 -->

    <div class="beian">
      <div style="width:300px;margin:0 auto; padding:20px 0;">
        <a
          target="_blank"
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=44060402002445"
          style="display:inline-block;text-decoration:none;height:20px;line-height:20px;"
        >
          <img src="@/assets/beian.png" style="float:left;" />
          <p
            style="float:left;height:20px;line-height:20px;margin: 0px 0px 0px 5px; color:#939393;"
          >粤公网安备 44060402002445号</p>
        </a>
        <a
          style="display:inline-block;text-decoration:none;height:20px;line-height:20px;"
          href="https://beian.miit.gov.cn"
        >
          <p
            style="float:left;height:20px;line-height:20px;margin: 0px 0px 0px 5px; color:#939393;"
          >粤ICP备2022117075号-1</p>
        </a>
      </div>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { bannerAPI } from "@/api/homepage.js";
import playlistitem from "@/components/playlist-item/index";
import playlistskeleton from "@/components/playlist-item/playlist-skeleton";
import musicItem from "@/components/music-item/music-item";
import { getsearchAPI } from "@/api/search";
import {
  personalizedAPI,
  recommendAPI,
  personalizednewSongsAPI,
} from "@/api/homepage.js";
import { mapState } from "vuex";
export default {
  name: "discover",
  //import引入的组件需要注入到对象中才能使用
  components: { playlistitem, playlistskeleton, musicItem },
  props: {},
  data () {
    //这里存放数据
    return {
      homedata: {},
      extInfo: {},
      playlist: {},
      loading: true,
      musics: [],
      discoverloading: true,
    };
  },
  //计算属性 类似于data概念
  computed: { ...mapState["isLogin"] },
  //监控data中的数据变化
  watch: {
    // 监听登录状态，更新歌单
    "$store.state.isLogin": {
      deep: true,
      handler () {
        this.getpersonalized();
      },
    },
  },
  //方法集合
  methods: {
    async playmusic (item) {
      if (item.url == null) {
        if (item.targetId != 0) {
          // 歌曲
          if (item.targetType == 1) {
            const { data } = await getsearchAPI(
              item.targetId,
              10,
              0,
              item.targetType
            );
            let bannersong = data.result.songs[0];
            this.$store.commit("addMusictoMusiclistbySearch", bannersong);
            this.$store.commit("getcurrentIndex", bannersong);
            this.$store.dispatch("getMusicDetail", bannersong);
          } else if (item.targetType == 10) {
            // 专辑
            this.$router.push({
              name: "album",
              query: { id: item.targetId },
            });
          }
        }
      }
    },
    //获取推荐歌单
    async getpersonalized () {
      // 判断登录状态
      try {
        if (this.$store.state.isLogin == false) {
          // console.log(this.$store.state.isLogin, "当前为未登录推荐歌单");
          const { data } = await personalizedAPI();
          this.playlist = data.result;
        } else if (this.$store.state.isLogin == true) {
          const { data } = await recommendAPI();
          // console.log(data, "登录推荐歌单");
          this.playlist = data.recommend;
          // 当推荐歌单不足10个的时候，通过通用推荐歌单进行填充
          if (this.playlist.length < 10) {
            const { data } = await personalizedAPI();
            this.playlist.push(...data.result);
          }
          this.playlist = this.playlist.slice(0, 10);
        }
        this.loading = false;
      } catch (error) {
        console.log(error + "获取推荐歌单失败");
      }
    },
    // 获取最新音乐
    async personalizednewSongs () {
      try {
        const { data } = await personalizednewSongsAPI();
        // console.log(data);
        this.musics = data.result;
      } catch (error) {
        console.log(error + "获取推荐音乐失败");
      }
    },
    //获取首页轮播图
    async gethomepage () {
      try {
        const { data } = await bannerAPI();

        this.extInfo = data.banners;
        this.discoverloading = false;
      } catch (error) {
        console.log(error + "获取失败");
      }
    },
    // 播放最新音乐的时候把这些音乐全部添加进备选列表
    addPlaylist (music) {
      let musicList = [];

      this.musics.forEach((Element) => {
        let Musicformat = {
          id: Element.id,
          name: Element.name,
          ar: Element.song.artists,
          al: Element.song.album,
          dt: Element.song.duration,
          mv: Element.song.mvid,
        };
        musicList.push(Musicformat);
      });

      this.$store.commit("addMusictoMuiscListbyNewmusic", musicList);
      // 传入当前歌曲
      this.$store.commit("getcurrentIndex", music);
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    // console.log("创建完成获取数据");
    this.gethomepage();
    this.getpersonalized();
    this.personalizednewSongs();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () { },
  beforeCreate () { }, //生命周期 - 创建之前
  beforeMount () { }, //生命周期 - 挂载之前
  beforeUpdate () { }, //生命周期 - 更新之前
  updated () { }, //生命周期 - 更新之后
  beforeDestroy () { }, //生命周期 - 销毁之前
  destroyed () {
    // console.log("推荐销毁");
  }, //生命周期 - 销毁完成
  activated () { }, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped lang='less'>
.discover {
  margin: 0 auto;
  width: 1200px;
  padding-top: 20px;
  //为音乐播放器留位置
  padding-bottom: 50px;
  .beian {
    padding-top: 80px;
    padding-bottom: 80px;
  }
  // 轮播图样式
  .discover-Carousel {
    /deep/ .el-icon-loading {
      color: #7e7e7e;
    }
    /deep/ .el-loading-text {
      color: #7e7e7e;
    }
    img {
      width: 600px;
      border-radius: 10px;
    }
    .el-carousel__item h3 {
      color: #475669;
      font-size: 14px;
      opacity: 0.75;
      line-height: 150px;
      margin: 0;
    }
  }
  // 歌单样式
  .discover-title {
    font-size: 30px;
    font-weight: 600;
    cursor: pointer;
    display: inline;
    text-decoration: none;
    color: #494949;
    a {
      color: #494949;
      text-decoration: none;
    }
    a:hover {
      color: #181818;
    }
  }
  .el-icon-arrow-right {
    font-weight: 900;
  }
  .line {
    margin-top: 20px;
    height: 3px;
    width: 100%;
    background-color: #9e9e9e;
  }

  .discover-playlist {
    display: flex;
    flex-wrap: wrap;
    .discover-playlist-item {
      margin-left: 30px;
      margin-right: 30px;
      margin-top: 20px;
    }
  }
  .discover-newmusic {
    display: flex;
    flex-wrap: wrap;
    .newmusic-item {
      width: 33.33%;
    }
  }
}
</style>